Uec3.PayInvoiceWindow=Ext.extend(Ext.Window,{
	constructor:function(){
		//Ext.applyIf(this,Ext.WindowGroupUec3.superclass.constructor.call(this));
		//this.constructor.prototype=Ext.WindowGroupUec3.superclass.constructor.call();
	},
	objsCollection:new Ext.util.MixedCollection(false),
	getObjByKey:function(key){
		return this.objsCollection.get(key);
	},
	initAll:function(){
		initData();
		initComponents();
		//initFuns();
	},
	
	initData:function(){
		var payInvoiceItem_record=Ext.data.Record.create( [ {
			name : 'id',
			type : 'int',
			mapping : 'id'
		}, {
			name : 'companyId',
			type : 'int',
			mapping : 'companyId'
		},{
			name : 'code',
			type : 'string',
			mapping : 'code'
		}, {
			name : 'documentType',
			type : 'int',
			mapping : 'documentType'
		}, {
			name : 'documentId',
			type : 'int',
			mapping : 'documentId'
		}, {
			name : 'payable',
			type : 'double',
			mapping : 'payable'
		}, {
			name : 'paid',
			type : 'double',
			mapping : 'paid'
		}, {
			name : 'customerId',
			type : 'string',
			mapping : 'customerId'
		}, {
			name : 'customerName',
			type : 'string',
			mapping : 'customerName'
		}, {
			name : 'documentTypeVarName',
			type : 'string',
			mapping : 'documentTypeVarName'
		}]);
		this.payInvoiceItem_record=payInvoiceItem_record;
		var payInvoiceItem_url_store=new Ext.data.JsonStore({
			url:Uec3.App.Constants.homeUrl+"/payable/base!getPayablesBycustomerId.do",
			root:'root',
			pruneModifiedRecords:true,
			fields:payInvoiceItem_record
		});
		this.objsCollection.add("payInvoiceItem_url_store",payInvoiceItem_url_store);
		var payInvoiceItem_store=new Ext.data.JsonStore({	
		 	    //remoteSort:false,
		        root: "",
		        idProperty: "id",
		        pruneModifiedRecords:true,
		        fields:payInvoiceItem_record
		     });
		this.objsCollection.add("payInvoiceItem_store",payInvoiceItem_store);
		var ds_partner_store = new Ext.data.JsonStore({
	     	url: Uec3.App.Constants.homeUrl+"/partner/query_partner!queryPartner.do",
	        id:"id",
	        root:'root',   
            totalProperty: 'totalProperty',  
	        remoteSort: true,   
	        baseParams:{start:0,limit:4},
	        fields: [
	        		 {name:'id',type:'int'},
	        		 {name:'pyCode',type:'string'},
	        		 {name:'name',type:'string'},
	        		 {name:'companyId',type:'int'}
	        		]
	     });	
	     this.objsCollection.add("ds_partner_store",ds_partner_store);
	},
	
	initComponents:function(){
		var win=this;
	    var partner_combox = new Ext.form.LookupBox2({
  			store: this.getObjByKey("ds_partner_store"),
  			//fieldLabel:'供货单位',
  			//name:'partnerIdByBuyer',
  			//id:"partnerName",
	        displayField:'name',
	        lookupField:'pyCode',
	        valueField:'id',
	        hiddenName:'customerId',
	        typeAhead: false,
	        mode: 'remote',
	        triggerAction: 'all',
	        emptyText:'输入拼音或名字查询供货商..',
	        selectOnFocus:true,
	        //applyTo: 'partner_lookup_combox',
	        queryParam:'queryParam',
	        queryDelay:10,
	        typeAheadDelay:10,
	        pageSize:4,
	        start:0,
	        app:win.app,
            triggerTags : [{moduleId: 'partner_query',triggerClass:'x-form-search-trigger'},{moduleId:'partner_add'}],
  	        listeners:{
  	           'select':function(){
  	           		var payInvoiceItem_url_store=win.getObjByKey('payInvoiceItem_url_store');
  	           		payInvoiceItem_grid.getStore().removeAll();
  	           		payInvoiceItem_url_store.load({params:{customerId:payInvoice_formPanel.getForm().findField('customerId').getValue()},callback:function(){
  	           			Ext.each(payInvoiceItem_url_store.getRange(),function(payable){
  	           			var record=win.getObjByKey("getPayInvoiceItemRecord")(payable.data,0);
  	           			payInvoiceItem_grid.getStore().add(record);
  	           			});
  	           		}});
               },
               'change':function(){
               		
               }
  	        }
	    });
		win.objsCollection.add("partner_combox",partner_combox);
		var payInvoice_documentType=Uec3.App.dictionary.getCombo("invoiceType",{hiddenName:"invoiceType",allowBlank:false});
		win.objsCollection.add("payInvoice_documentType",payInvoice_documentType);
		var payInvoice_panel_top=new Ext.Panel({
			frame:true,
			layout:'form',
			style:'text-align:center;fontSize:16px;',
			layoutConfig:{
			    margins:"10 10 0 10"
			},
			width : '100%',
			items : [{layout:'hbox',
			          xtype:'fieldset',
			          layoutConfig: {
	                      padding: 0,
	                      pack:'start'
                      },			         
			          border : false,
			          //padding:0,
	        		  style:'padding:0px;',
					  items:[{
								xtype : 'label',
								text : '供应商:',
								width : 50,
								style:'text-align:left;',
								anchor : '100%'
							},
								partner_combox
							,{
								xtype : 'label',
								text : '发票号:',
								width : 80,
								anchor : '100%'
							},{
								xtype : 'textfield',
								width : 100,
								name : 'codeOfSeller',
								//format : 'Y-m-d',
								anchor : '100%'
							},{
								xtype : 'label',
								text : '付款日期:',
								width : 80,
								anchor : '100%'
							},{
								xtype : 'datefield',
								width : 100,
								name : 'gmtActualPay',
								format : 'Y-m-d',
								anchor : '100%'
							},{
								xtype : 'label',								
								text : '发票类型:',
								width : 80,
								anchor : '100%'
							},payInvoice_documentType,{
								xtype : 'label',								
								text : '支付金额:',
								width : 80,
								anchor : '100%'
							},{
								xtype : 'numberfield',
								width : 100,
								readOnly:true,
								name : 'amount',
								anchor : '100%'
							},{
								xtype:'hidden',
								name:'id'
							}
							]},
							{xtype:'fieldset',
				            border:false,
				            layout:'hbox',
				            style:'padding:0px;',
				            items:[{
										xtype : 'label',								
										text : '备注:',
										width : 50,
										style:'text-align:left;',
										anchor : '100%'
									},{
										xtype : 'textfield',
										width : '90%',
										name : 'memo'
									}]
				            }]
				
						
		});
		win.objsCollection.add("payInvoice_panel_top",payInvoice_panel_top);
		var payInvoice_panel_bottom=new Ext.Panel({
			frame:true,
			layout:'form',
			style:'text-align:center;fontSize:16px;',
			layoutConfig:{
			    margins:"0 0 0 0"
			    
			},
			width : '100%',
			items : [{
				layout:'hbox',
		        xtype:'fieldset',
		        layoutConfig: {
	            	padding: 0,
	                pack:'start'
		        },	
		        padding:0,
		        style:'padding:0px;',
		        border : false,
					items:[{
								xtype : 'label',
								text : '单据状态:',
								width : 80,
								style: "text-align: left;", 
								anchor : '100%'
							},{
								xtype : 'textfield',
								width : 100,
								name : 'statusVarName',
								anchor : '100%'
							},{
								xtype : 'label',
								text : '创建人:',
								width : 100,
								
								anchor : '100%'
							},{
								xtype : 'textfield',
								width : 100,
								name : 'currentorName'
							},{
								xtype : 'label',
								text : '创建时间:',
								
								width : 100,
								anchor : '100%'
							},{
								xtype : 'textfield',
								width : 100,
								name : 'gmtCreate',
								format : 'Y-m-d',
								anchor : '100%'
							},{
								xtype : 'label',								
								text : '支付人:',
								width : 100,
								anchor : '100%'
							},{
								xtype : 'textfield',
								width : 100,
								name : 'payerName',
								anchor : '100%'
							},{
								xtype : 'label',								
								text : '支付时间:',
								width : 100,
								anchor : '100%'
							},{
								xtype : 'textfield',
								width : 100,
								name : 'gmtPay',
								format : 'Y-m-d',
								anchor : '100%'
							}]	
			         }]
		});
		win.objsCollection.add("payInvoice_panel_bottom",payInvoice_panel_bottom);				
		var payInvoiceItem_cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), 
			{
			header:'操作',
			width:50,
			dataIndex:'id',
			renderer:renderDel
			},
			{
			header : '应付款凭证号',
			width : 75,
			sortable : true,
			dataIndex : 'code'
			}, 
			{
			header : '供应商',
			width : 75,
			sortable : true,
			dataIndex : 'customerName'
			}, 
			{
			header : '单据类型',
			width : 75,
			sortable : true,
			dataIndex : 'documentTypeVarName'
			}, 
			{
			header : '应付金额',
			width : 75,
			sortable : true,
			dataIndex : 'payable'
			}, 
			{
			header : '支付金额',
			width : 75,
			sortable : true,
			dataIndex : 'paid',
			editor:new Ext.form.NumberField({
		        allowBlank: false,
		        allowNegative: false
	     	})
		}]);
		var payInvoiceItem_grid=new Ext.grid.EditorGridPanel({
	        cm:payInvoiceItem_cm,
			store : payInvoiceItem_store,
			selModel : new Ext.grid.RowSelectionModel( {
				moveEditorOnEnter : true
			}),
			iconCls : 'icon-grid',
			loadMask : {
				msg : '数据加载中...'
			},
			clicksToEdit:1,
			tbar: [{
				text: "添加",
				iconCls:'icon-add',
				handler: function(){
					  
				}
			}],
			stripeRows : true,
			autoScroll : true,
			//autoload : true,
			height : 250,
			width : '100%',
			listeners : {
			}
		});				
		win.objsCollection.add("payInvoiceItem_grid",payInvoiceItem_grid);					
		/* FormPanel */
		var payInvoice_formPanel = new Ext.FormPanel({
			labelAlign : 'right',
			frame : true,
			formId : 'payInvoice_form',
			//title:'付款单',
			items : [payInvoice_panel_top,payInvoiceItem_grid,payInvoice_panel_bottom]
		});
		win.objsCollection.add("payInvoice_formPanel",payInvoice_formPanel);
	},
	
	initFuns:function(){
		var win=this;
		var wMaskCol=new Ext.util.MixedCollection(false);
	   	var windowLoadMask;
	   	var buttonAjax=new Ext.data.Connection();
	   	Ext.util.Observable.capture(buttonAjax,function(e){
	   		if(e=='beforerequest'){
	   			//if(windowLoadMask)windowLoadMask.show();
	   			Ext.MessageBox.show({
	                title : "提示",
	                msg : "加载中,请稍后.....",
	                buttons: false,
	                closable:false,
	                wait:true,
	                modal:false,
	                minWidth: this.minProgressWidth
	              
	            });
	   		}else if(e=='requestcomplete'){
	   			Ext.MessageBox.hide();
	   		}
	   	});
			  	
		var operation=function(btn){
			eval(btn.func+"(btn)");
		}
		/*新建单据*/
		function payInvoiceNew(btn){
			window.location.href=btn.url;
		}
		/*接手单据*/
	    function payInvoiceRecieve(btn){
	    	Ext.Msg.confirm("提示",((payInvoice.currentorName==null||payInvoice.currentorName=='')?"无人":payInvoice.currentorName)+"在处理,确定要接手?",function(btn2){
				if(btn2=="yes"){
					formSubmit(btn.url);
				}
			});
		}
		/*释放单据*/
		function payInvoiceRelease(btn){
			var fn=function(){
				payInvoice.currentorName=null;
			}
			formSubmit(btn.url,fn);
		}
		function payInvoiceReset(){
			Ext.Msg.confirm("提示","确定置空所有的行",function(btn){
				if(btn=="yes"){
					initialFormPanel.getForm().reset();
					formSubmit("/initialItem/base!delByInitialId?initialId="+id,function(){
						ds_initialItem.reload();
			        });
				}
			});
		}
		/*查看付款单列表*/
		function payInvoiceView(){
			window.location.href='/payInvoice/base!extIndex.do';
		}		
		function formSubmit(url,fn){
			var result;
			var findField=payInvoice_formPanel.getForm().findField('amount').getValue();
			var payInvoiceJson=Ext.encode(encodeFilte(payInvoice_formPanel.getForm().getValues()));
			var payInvoiceItems=[];
			Ext.each(payInvoiceItem_grid.getStore().getRange(),function(record){
				payInvoiceItems.push(record.data);
			});
			var payInvoiceItemJson=Ext.encode(encodeFilte(payInvoiceItems));
			payInvoice_formPanel.form.submit({
				waitMsg:'请稍后.....',
				waitTitle:'提示',
				url:Uec3.App.Constants.homeUrl+url,
		        method :"post",
		        params:{'payInvoiceJson':payInvoiceJson,'payInvoiceItemJson':payInvoiceItemJson},
		        success:function(form,action){
		      		result=action.result;
		      		if(result.failure){
		      			Ext.Msg.alert('信息','操作失败!');
		      			return;
		      		}else {
			  			removeButtons();
			  			initButtons(result.buttons,operation,payInvoice_formPanel);
			  			//isMark(result.isMark);
			  			if(Ext.isFunction(fn))fn(result);
			  			if(result.msg){
			  				Ext.Msg.alert('信息',msg); 
			  			}
		      		}
		       	},
		        failure:function(form,action){
		        	Ext.Msg.alert('提示','网络问题,操作失败!');
		      	}
			});
			return result;
		}
		/*保存*/
		function payInvoiceSave(btn){
			if(payInvoice_formPanel.getForm().isValid()){
				if(isItemGridValid()){
					var result=formSubmit(btn.url,function(result){
						if(result.payInvoice){
							payInvoice_formPanel.getForm().setValues(result.payInvoice);
						}
						if(result.payInvoiceItemList){
							var store=payInvoiceItem_grid.getStore();
							Ext.each(result.payInvoiceItemList,function(payInvoiceItem){
								Ext.each(store.getRange(),function(payable){							
									if(payInvoiceItem.payableId==payable.data.payableId){
										payable.set("id",payInvoiceItem.id);
									}
								});
							});
						}
					});
				}else{
					Ext.Msg.alert('提示','请至少加一条明细记录  ');
				}
			}else{
				Ext.Msg.alert('提示','请填写必填项');
			}	
		}
		/*提交*/
		function payInvoiceSubmit(btn){
			saveOrSubmit(btn);
		}
		function saveOrSubmit(btn){
			if(payInvoice_formPanel.getForm().isValid()){
				if(isItemGridValid()){
					var result=formSubmit(btn.url,function(result){
						if(result.payInvoice){
							payInvoice_formPanel.getForm().setValues(result.payInvoice);
						}
	/*					if(result.payInvoiceItemList){
							var store=payInvoiceItem_grid.getStore();
							store.removeAll();
							Ext.each(result.payInvoiceItemList,function(payInvoiceItem){
								var record=getPayInvoiceItemRecord(payInvoiceItem,1);
								store.add(record);
							});
						}*/
					});
				}else{
					Ext.Msg.alert('提示','请至少加一条明细记录  ');
				}
			}else{
				Ext.Msg.alert('提示','请填写必填项');
			}
		}
		/*删除*/
		function payInvoiceDelete(){
			Ext.Msg.confirm("提示","确定删除",function(btn){
				if(btn=="yes"){
				    formSubmit(Uec3.App.Constants.homeUrl+"/initialItem/base!delByInitialId?initialId="+id);
					//window.location.href='/initial/base!extIndex.do';
				}
			});
		}
		/*打印*/
		function payInvoicePrint(){
			
		}
		/*返回*/
		function payInvoiceBack(){
			
		}
		/*遮罩层*/
	  	var maskFieldset;
	  	var maskGridTopbar;
		function isMark(isMark){
		  if(isMark=="true"||isMark==true){
		  	if(!maskFieldset&&!maskGridTopbar){
	  			maskFieldset = new Ext.LoadMaskJUPIT("maskFieldset");
		  		maskGridTopbar=new Ext.LoadMaskJUPIT(initialItem_grid.getTopToolbar().id);
		  	}
	     	maskFieldset.show();
	     	maskGridTopbar.show();
			}else {
				if(maskFieldset&&maskGridTopbar){
					maskFieldset.hide();
					maskGridTopbar.hide();
				}
			}
		}
		
		function init() {
			if(payInvoice.id!=null){
		    	payInvoiceItem_store.load({"id":payInvoice.id});//加载payInvoiceItem的记录
			}else{
			}
		}
		Ext.util.Observable.capture(payInvoice_formPanel,function(e){
			if(e=="beforerender"){
				payInvoice_documentType.getStore().load();	//获得单据类型combox数据
			}
			if(e=='render'){
				windowLoadMask=new Ext.LoadMask(payInvoice_formPanel.ownerCt.id);
	   			windowLoadMask.show();
				var grid=payInvoice_formPanel.items.get(1);
				if(params&&params.id){
					payInvoice_formPanel.getForm().load({
						url:Uec3.App.Constants.homeUrl+'/payInvoice/base!getPayInvoiceById.do',
		   				params:{id:params.id},
		   				success:function(form,action){
		   					isMaskWindow("initialFormPanel");
		   					if(action.result.success=='OK'){
			   					var payInvoice=action.result.payInvoice;
			   					var userId=action.result.userId;
			   					if(payInvoice.status==0){
			   						if(payInvoice.currentorId==payInvoice){
			   							buttonAjaxRequest("currentorModify",false);
			   						}else{
			   							buttonAjaxRequest("notCurModify",true);
			   						}
			   					}else if(payInvoice.status==1){
			   						buttonAjaxRequest("formal",true);
			   					}
			   					
			   					if(!Ext.isEmpty(grid)&&Ext.ptype=='grid'){
			   						grid.getStore().baseParams={
										'payInvoiceId':Ext.isEmpty(payInvoice.id)?0:payInvoice.id
									}
									grid.getStore().load();
			   					}else{
			   						Ext.Msg.alert("错误","获得grid对象出错");
			   					}
			   					var partner=action.result.partner;
			   					if(partner){
									partner_combox.initializeValue({'name':partner.name,'pyCode':partner.pyCode,'id':partner.id});
								}
		   					}else{
		   						Ext.Msg.alert("错误",action.result.success);
		   					}
		   				},
		   				failure:function(){
		        			Ext.Msg.alert('网络延迟或断网,请稍后连接');
		        			isMaskWindow("initialFormPanel");
	    				}
					});; //设置表单数据
				}else if(params&&params.payableIds){
					Ext.Ajax.request({
						url:Uec3.App.Constants.homeUrl+'/payInvoice/base!createFormPayable.do',
		   				params:{payableIds:params.payableIds,customerId:params.customerId},
		   				success:function(form,action){
		   					var result=Ext.decode(form.responseText);
		   					var payableList=result.payableList;
		   					var partner=result.partner;
							if(partner){
								partner_combox.initializeValue({'name':partner.name,'pyCode':partner.pyCode,'id':partner.id});
							}
							if(payableList.length>0){
								Ext.each(payableList,function(payable){
									var record=getPayInvoiceItemRecord(payable,0);
									grid.getStore().add(record);
								});
							}
							isMaskWindow("initialFormPanel");
							buttonAjaxRequest("new",false);
		   				},
		   				failure:function(){
		        			Ext.Msg.alert('网络延迟或断网,请稍后连接');
		        			isMaskWindow("initialFormPanel");
	    				}
					});
				}else{
					isMaskWindow("initialFormPanel");
					buttonAjaxRequest("new",false);
				}
				
			}
		});
		function isMaskWindow(obj){
	    	wMaskCol.add({id:obj});
	    	if(windowLoadMask&&wMaskCol.getCount()==2){
	    		windowLoadMask.hide();
	    		wMaskCol.clear();
	    	}
	    }
		//payInvoice_formPanel.render("payInvoice_div");
		//改变金额显示
		Ext.util.Observable.capture(payInvoiceItem_store,function(e){
			try{   
	        if(e=='add'||e=='remove'||e=='update'||e=='load'){
	        	calAmount();
	        }
	      	}catch(e){   
	        	alert(e);   
	      	}   
		});
		Ext.util.Observable.capture(payInvoiceItem_grid.getView(),function(e){
			try{   
	        if(e=='rowsinserted'||e=='rowupdated'){
	        	addDeleteListens();
				calAmount();
	        }
	      	}catch(e){   
	        	alert(e);   
	      	}   
		});
		
		//删除按钮
		Ext.util.Observable.capture(payInvoiceItem_grid,function(e){
			try{
			if(e=='viewready'){
				addDeleteListens();
				calAmount();
			}
			}catch(e){
				alert(e);
			}
		});
		
		//计算金额
		function calAmount(){
			var records=payInvoiceItem_store.getRange();
	    	var amount=0;
	    	Ext.each(records,function(record){
				amount+=record.get('paid');	        	
	    	});
	    	payInvoice_formPanel.getForm().setValues({'amount':amount})
		}
		//删除链接渲染
		function renderDel(value,metadata,record,rowIndex){
			var arr=[];
			var res="";				
			arr.push('<a href="#" id="del'+record.id+'">删除</a>');
			Ext.each(arr,function(obj){
				res+=obj+" | ";
			});
			res=res.substring(0,res.length-3);
			return res;
		}	
		function payInvoiceItemDelete(id){
			var store=payInvoiceItem_grid.getStore();
			var record=store.getById(id);
			store.remove(record);
		}
		function addDeleteListens(){
			var records=payInvoiceItem_grid.getStore().getRange();
			Ext.each(records,function(record){
				Ext.get("del"+record.id).on('click',function(){
					payInvoiceItemDelete(this.id.substring(3,this.id.length));
				});
			});	
		}
		function encodeFilte(o){
			if(Ext.isArray(o)){
				Ext.each(o,function(obj){
					obj=encodeFilte(obj);
				});
			}else{
				for(pro in o){
					if(!o[pro]){
						o[pro] = undefined;		
					}
				}
			}
			return o
		}
		function getPayInvoiceItemRecord(obj,type){
			//type:0表示从payable传过来的,1表示从payInvoiceItem传过来的
			var record=new payInvoiceItem_record();
			if(type==0){
				record.set("code",obj.code);
				record.set("customerId",obj.customerId);
				record.set("customerName",obj.customerName);
				record.set("payableId",obj.id);
				record.set("documentTypeVarName",obj.documentTypeVarName);
				record.set("payable",obj.payable-obj.paid);
				record.set("paid",obj.payable-obj.paid);
			}else if(type==1){
				record.set("id",obj.id);
				record.set("code",obj.code);
				record.set("customerId",obj.customerId);
				record.set("customerName",obj.customerName);
				record.set("payableId",obj.payableId);
				record.set("documentTypeVarName",obj.documentTypeVarName);
				record.set("payable",obj.payable);
				record.set("paid",obj.paid);
			}
			return record;
		}
		function isItemGridValid(){
	   		var obj=payInvoice_formPanel.form.getValues();
	   		if(obj.id){
	   			return true;
	   		}else{
	   			if(payInvoiceItem_grid.getStore().getCount()>0){
	   				return true;
	   			}
	   		}
	   		return false;
	   	}
	   	
	   	//按钮加载
	   	function buttonAjaxRequest(typeId,mark,fn){
	   		buttonAjax.request({
			 	url:Uec3.App.Constants.homeUrl+'/initial/buttonPanel.do',
			 	params:{typeId:typeId},
			 	success:function(response,options){
			 		isMaskWindow("buttons");
			 		var reslut = Ext.decode(response.responseText);
			 		removeButtons(payInvoice_formPanel);
			 		initButtons(reslut.buttons,operation,payInvoice_formPanel);// 初始按钮
			 		//是否遮罩
	   				isMark(mark);
			 		//isMaskWindow("buttons");
	   				payInvoice_formPanel.ownerCt.doLayout();
	   				if(Ext.isFunction(fn))fn(reslut);
			 	}
			});
	   	}
	}
});
